package com.dlwx.firefighting.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.dlwx.firefighting.R;
import com.dlwx.firefighting.bean.AddressBean;
import com.dlwx.firefighting.bean.ProvinceBean;
import com.dlwx.firefighting.config.Constant;
import com.dlwx.firefighting.utils.CheckUtil;
import com.dlwx.firefighting.utils.DialogUtils;
import com.dlwx.firefighting.utils.KeyBoardUtils;
import com.dlwx.firefighting.utils.SPUtils;
import com.dlwx.firefighting.utils.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.zhy.autolayout.AutoRelativeLayout;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 添加收货地址界面
 */
public class AddAddressActivity extends BaseActivity {

    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.address_edit_name)
    EditText editName;
    @BindView(R.id.address_edit_phone)
    EditText editPhone;
    @BindView(R.id.address_tv_city)
    TextView tvCity;
    @BindView(R.id.rel_address_select)
    AutoRelativeLayout relSelect;
    @BindView(R.id.address_edit_write)
    TextInputEditText editWrite;
    @BindView(R.id.address_button_save)
    TextView btnSave;
    @BindView(R.id.address_button_delete)
    TextView addressButtonDelete;
    @BindView(R.id.title_right_one_tv)
    TextView titleRightOneTv;
    @BindView(R.id.ll_default)
    AutoRelativeLayout llDefault;


    private String name;
    private String phone;
    private String cityInfo;
    private String details_info;
    private String userId;
    private String action;
    private String addressId = "";
    private String provinceId = "";
    private String cityId = "";
    private String areaId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_address);
        ButterKnife.bind(this);
        userId = (String) SPUtils.get(this, Constant.USER_ID, "");
        AddressBean bean = (AddressBean) getIntent().getSerializableExtra("bean");
        if (bean != null) {
            action = "update";
            initDatas(bean);
            btnSave.setText("设置默认地址");
            addressButtonDelete.setVisibility(View.VISIBLE);
            titleRightOneTv.setVisibility(View.VISIBLE);
//            titleRightOneTv.setText("保存");
            titleRightOneTv.setText("保存");
            llDefault.setVisibility(View.GONE);
        } else {
            addressButtonDelete.setClickable(false);
            addressButtonDelete.setBackgroundResource(R.drawable.bg_grey);
            action = "add";
//            btnSave.setText("保存");
            titleRightOneTv.setText("保存");
            addressButtonDelete.setVisibility(View.GONE);
            llDefault.setVisibility(View.VISIBLE);
        }
        initView();

    }

    private void initDatas(AddressBean bean) {
        editName.setText(bean.getConsignee());
        editPhone.setText(bean.getMobile());
        cityInfo = bean.getAddress();
        tvCity.setText(cityInfo);
        addressId = bean.getAddress_id();
        name = bean.getConsignee();
        phone = bean.getMobile();
        provinceId = bean.getProvince();
        cityId = bean.getCity();
        areaId = bean.getDistrict();
    }

    private void initView() {
        titleLeftOneBtn.setVisibility(View.VISIBLE);
        titleRightOneTv.setVisibility(View.VISIBLE);
        tvMiddleTitle.setText("添加新地址");
        editName.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    editName.setCursorVisible(true);
                }
                return false;
            }
        });
    }

    @OnClick({R.id.title_left_one_btn, R.id.rel_address_select, R.id.address_button_save, R.id.address_button_delete, R.id.title_right_one_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_one_btn:
                finish();
                break;
            case R.id.rel_address_select:  //选择地址
                Intent i = new Intent(AddAddressActivity.this, AddressSelectActivity.class);
                startActivityForResult(i, 0);
//                selectCity();
                break;
            case R.id.address_button_delete:  //删除
                action = "del";
                saveAddress();
                break;
            case R.id.address_button_save:  //保存收货地址到数据库
                KeyBoardUtils.closeKeybord(this);
                if (checkInputInfo()) {
                    saveAddress();
                }
                break;
            case R.id.title_right_one_tv:  //保存
                KeyBoardUtils.closeKeybord(this);
                if (checkInputInfo()) {
                    action = "save";
                    saveAddress();
                }
                break;

        }
    }

    private void saveAddress() {
        DialogUtils.showProgressDlg(this, "");
      /*  update 设置默认地址
        add 添加地址
        del 删除地址
        save 保存地址*/

        OkGo.<String>post(Constant.ADDRESS_ACTION)
                .tag(this)
                .params("user_id", userId)
                .params("act", action)
                .params("address_id", 21)
                .params("consignee", name)
                .params("tel", phone)
                .params("address", cityInfo)
                .params("province", provinceId)
                .params("city", cityId)
                .params("district", areaId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
//                        DealResult dealResult = new DealResult();
//                        BaseBean bean = dealResult.dealBaseRes(AddAddressActivity.this, response);
//                        if (bean != null) {
//                            if (bean.getStatus() == Constant.SUCESS) {
//                                AddAddressActivity.this.finish();
//                            }
//                            ToastUtils.toastForShort(AddAddressActivity.this, bean.getMsg());
//                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(AddAddressActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    /**
     * 检查收货人信息和地址信息
     */
    private boolean checkInputInfo() {
        name = editName.getText().toString();
        phone = editPhone.getText().toString();
        cityInfo = tvCity.getText().toString();
        details_info = editWrite.getText().toString();

        if (TextUtils.isEmpty(name)) {
            ToastUtils.toastForShort(this, "收货人姓名不能为空");
            return false;
        }
        if (!CheckUtil.isPhoneNum(phone)) {
            ToastUtils.toastForShort(this, "手机号信息错误");
            return false;
        }
        if (TextUtils.isEmpty(cityInfo)) {
            ToastUtils.toastForShort(this, "未选择省市县");
            return false;
        }
      /*  if (TextUtils.isEmpty(details_info)) {
            ToastUtils.toastForShort(this, "未填写详细信息");
            return false;
        }*/
        return true;
    }

    /**
     * 选择城市
     */
   /* private void selectCity() {
        KeyBoardUtils.closeKeybord(this);
        CityPicker cityPicker = new CityPicker.Builder(AddAddressActivity.this)
                //.textSize(20)
                .title(" ")
                //.titleTextColor("#3F51B5")
                .titleBackgroundColor("#ffffff")
                .backgroundPop(0xa0000000)
                .confirTextColor("#3F51B5")
                .cancelTextColor("#3F51B5")
                .province("河南省")
                .city("开封市")
                .district("通许县")
                .textColor(Color.parseColor("#333333"))
                .provinceCyclic(true)
                .cityCyclic(false)
                .districtCyclic(false)
                .visibleItemsCount(7)
                //.itemPadding(10)
                .onlyShowProvinceAndCity(false)
                .build();
        cityPicker.show();

        //监听方法，获取选择结果
        cityPicker.setOnCityItemClickListener(new CityPicker.OnCityItemClickListener() {
            @Override
            public void onSelected(String... citySelected) {
                //省份
                String province = citySelected[0];
                //城市
                String city = citySelected[1];
                //区县（如果设定了两级联动，那么该项返回空）
                String district = citySelected[2];
                //邮编
                String code = citySelected[3];

                tvCity.setText(province + "  " + city + "  " + district);
            }

            @Override
            public void onCancel() {
                Toast.makeText(AddAddressActivity.this, "已取消", Toast.LENGTH_LONG).show();
            }
        });
    }*/

    ProvinceBean provinceBean;
    ProvinceBean.CityArrayBean cityArrayBean;
    ProvinceBean.CityArrayBean.AreaArrayBean areaArrayBean;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 1) {
            provinceBean = (ProvinceBean) data.getSerializableExtra("province");
            cityArrayBean = (ProvinceBean.CityArrayBean) data.getSerializableExtra("city");
            areaArrayBean = (ProvinceBean.CityArrayBean.AreaArrayBean) data.getSerializableExtra("area");
            tvCity.setText(provinceBean.getName() + "  " + cityArrayBean.getName() + "  " + areaArrayBean.getRegion_name());
            provinceId = provinceBean.getId();
            cityId = cityArrayBean.getId();
            areaId = areaArrayBean.getRegion_id();
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    //------------------------------------------------
}
